# -*- coding: utf-8 -*-
import logging
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
from django.contrib import messages
from django.urls import reverse

from app.services.amazon_sp_auth_service import AmazonOAuthService  # 修正导入，移除多余空格
 
logger = logging.getLogger(__name__)

class AmazonAuthView(View):
    """Amazon授权视图"""
    
    def __init__(self):
        super().__init__()
        self.oauth_service = AmazonOAuthService()
    
    def get(self, request):
        """显示授权页面或处理授权回调"""
        # 检查是否是授权回调
        code = request.GET.get('code')
        state = request.GET.get('state')
        error = request.GET.get('error')
        
        if error:
            # 处理授权错误
            error_description = request.GET.get('error_description', '')
            logger.error(f"Amazon auth error: {error} - {error_description}")
            return render(request, 'amazon_auth/error.html', {
                'error': error,
                'error_description': error_description
            })
        
        if code:
            # 处理授权回调
            return self._handle_callback(request, code, state)
        else:
            # 显示授权页面
            return self._show_auth_page(request)
    
    def _show_auth_page(self, request):
        """显示授权页面"""
        # 生成回调URL
        redirect_uri = request.build_absolute_uri(reverse('amazon_auth'))
        
        # 生成授权URL
        try:
            auth_url, state = self.oauth_service.generate_auth_url(redirect_uri)
            
            context = {
                'auth_url': auth_url,
                'state': state,
            }
            
            return render(request, 'amazon_auth/authorize.html', context)
            
        except Exception as e:
            logger.error(f"Failed to generate auth URL: {str(e)}")
            return render(request, 'amazon_auth/error.html', {
                'error': 'Configuration Error',
                'error_description': 'Failed to generate authorization URL'
            })
    
    def _handle_callback(self, request, code, state):
        """处理授权回调"""
        redirect_uri = request.build_absolute_uri(reverse('amazon_auth'))
        
        try:
            # 使用授权码换取访问令牌
            token_data = self.oauth_service.exchange_code_for_tokens(
                code=code,
                redirect_uri=redirect_uri,
                state=state
            )
            
            # 获取卖家信息
            seller_info = self.oauth_service.get_seller_info(
                access_token=token_data['access_token']
            )
            
            # 提取卖家ID
            seller_id = None
            if 'payload' in seller_info:
                for participation in seller_info['payload']:
                    if 'seller' in participation:
                        seller_id = participation['seller']['sellerId']
                        break
            
            if not seller_id:
                raise ValueError("Unable to get seller ID from Amazon")
            
            # 保存店铺认证信息
            store = self.oauth_service.save_store_credentials(
                seller_id=seller_id,
                credentials_data=token_data,
                user_id=request.user.id if request.user.is_authenticated else None
            )
            
            # 成功页面
            context = {
                'success': True,
                'seller_id': seller_id,
                'store_name': store.store_name,
                'expires_at': token_data['expires_at'],
            }
            
            return render(request, 'amazon_auth/success.html', context)
            
        except Exception as e:
            logger.error(f"Auth callback failed: {str(e)}")
            return render(request, 'amazon_auth/error.html', {
                'error': 'Authorization Failed',
                'error_description': str(e)
            })

@method_decorator(csrf_exempt, name='dispatch')
class AmazonWebhookView(View):
    """Amazon Webhook处理视图"""
    
    def post(self, request):
        """处理Amazon推送的通知"""
        try:
            # 这里可以处理Amazon的推送通知
            # 比如订单状态变更、库存变更等
            
            return JsonResponse({'status': 'success'})
            
        except Exception as e:
            logger.error(f"Webhook processing failed: {str(e)}")
            return JsonResponse({'error': str(e)}, status=400)

class AmazonStoreListView(View):
    """Amazon店铺列表视图"""
    
    def get(self, request):
        """显示已授权的Amazon店铺列表"""
        from app.models import AmazonStore  # 本地导入避免循环导入
        
        stores = AmazonStore.objects.filter(is_active=True)
        
        if request.user.is_authenticated:
            stores = stores.filter(user=request.user)
        
        context = {
            'stores': stores,
        }
        
        return render(request, 'amazon_auth/store_list.html', context)

def amazon_auth_test(request):
    """Amazon授权测试函数"""
    return JsonResponse({'message': 'Amazon auth test endpoint'})